<template>
  <el-dialog
    :close-on-click-modal="false"
    :title="isEdit ? '修改业务员' : '新增业务员'"
    width="900px"
    :visible.sync="visible"
  >
    <el-form
      class="edit-people-form"
      :model="form"
      ref="form"
      label-width="70px"
      :rules="rules"
      :inline="true"
    >
      <el-row class="mb10">
        <el-col>
          <el-form-item v-show="false" class="name-label1" label="ID">
            <el-input :disabled="true" v-model="form.linkmanId" />
          </el-form-item>
          <el-form-item label="供应商" class="supplier-label" prop="supplierCode">
            <supplier-select
              style="width: 100%"
              :selectValue="form.supplierCode"
              v-model="form.supplierCode"
              @select="handleSelect"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item class="name-label" label="姓名">
            <el-input
              placeholder="请输入"
              v-model="form.linkmanName"
              v-decorator="['linkmanName', { rules: [{required: true, message: '请输入姓名'}], validateTrigger: 'change' }]"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="头衔" class="name-label">
            <el-input
              placeholder="请输入"
              v-model="form.linkmanTitle"
              v-decorator="['linkmanTitle', { rules: [{required: true, message: '请输入头衔'}], validateTrigger: 'change' }]"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item class="name-label" label="手机">
            <el-input
              placeholder="请输入"
              v-model="form.linkmanTel"
              v-decorator="['linkmanTel', { rules: [{required: true, message: '请输入联系电话', pattern: /^1[3456789]\d{9}$/}], validateTrigger: 'change' }]"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item class="idcard-label" label="身份证号">
            <el-input placeholder="请输入" v-model="form.idcard" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item class="date-label" label="身份证到期日期">
            <el-date-picker
              value-format="yyyy-MM-dd"
              v-model="form.idcardEnd"
              type="date"
              placeholder="上传识别输入或选择日期"
            />
            <!-- <el-input placeholder="上传识别输入" v-model="form.idcardEnd" /> -->
          </el-form-item>
          <el-form-item v-show="false" class="date-label1" label="身份证前ID">
            <el-input
              :disabled="true"
              v-model="form.idcardFront"
              v-decorator="['idcardFront', { rules: [], initialValue: null }]"
            />
          </el-form-item>
          <el-form-item v-show="false" class="date-label1" label="身份证后ID">
            <el-input
              :disabled="true"
              v-model="form.idcardBack"
              v-decorator="['idcardBack', { rules: [], initialValue: null }]"
            />
          </el-form-item>
          <el-form-item v-show="false" label="营销资格证ID">
            <el-input
              :disabled="true"
              v-model="form.qualification"
              v-decorator="['qualification', { rules: [], initialValue: null }]"
            />
          </el-form-item>
        </el-col>
        <el-col :span="18">
          <el-form-item class="date-label1" label="购销资格证到期日期">
            <el-date-picker
              value-format="yyyy-MM-dd"
              v-model="form.qualificationEnd"
              type="date"
              placeholder="上传识别输入或选择日期"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="8">
          <el-form-item>
            <a-upload
              listType="picture-card"
              :fileList="idcardFront"
              class="avatar-uploader"
              :beforeUpload="beforeUpload"
              @preview="handlePreview"
              @change="info => handleChange(info, 1)"
              :customRequest="info => customRequest(info, 'front')"
              :remove="info => handleRemove(info, 'front')"
              v-decorator="['frontImg', {rules: []}]"
            >
              <div v-if="idcardFront.length < 1">
                <img style="width: 240px" :src="idcardZ" alt="示例" />
                <div class="ant-upload-text">身份证正面示例图片，点击上传</div>
              </div>
            </a-upload>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <a-upload
            listType="picture-card"
            :fileList="idcardBack"
            class="avatar-uploader"
            :beforeUpload="beforeUpload"
            @preview="handlePreview"
            @change="info => handleChange(info, 2)"
            :customRequest="info => customRequest(info, 'back')"
            :remove="info => handleRemove(info, 'back')"
            v-decorator="['backImg', {rules: []}]"
          >
            <div v-if="idcardBack.length < 1">
              <img style="width: 240px" :src="idcardF" alt="示例" />
              <div class="ant-upload-text">身份证反面示例图片，点击上传</div>
            </div>
          </a-upload>
        </el-col>
        <el-col :span="8">
          <a-upload
            listType="picture-card"
            :fileList="qualificationList"
            class="avatar-uploader"
            :beforeUpload="beforeUpload"
            @preview="handlePreview"
            @change="info => handleChange(info, 3)"
            :customRequest="customRequest"
            :remove="info => handleRemove(info, 'qualification')"
            v-decorator="['qualificationImg', {rules: []}]"
          >
            <div v-if="qualificationList.length < 1">
              <img style="width: 240px" :src="demoImg" alt="示例" />
              <div class="ant-upload-text">购销资格证示例图片，点击上传</div>
            </div>
          </a-upload>
          <preview-modal ref="previewModal" />
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" style="text-align: center">
      <el-button size="large" class="mr20" @click="handleCancel">取消</el-button>
      <el-button
        size="large"
        @click="handleOk"
        type="primary"
        :loading="confirmLoading"
      >{{ isEdit ? '修改' : '新增' }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import idcardZ from '@/assets/idcard_z.jpeg'
import idcardF from '@/assets/idcard_f.jpeg'
import demoImg from '@/assets/license.jpeg'
import { saveOnlyUploads, updateLinkMan, insertLinkMan, allLinkInfo, idcardFrontUpload, idcardBackUpload, showUrlById, deleteUploadPic } from '@/api/supplier'
import { openNotification, getBase64 } from '@/utils/util'
import PreviewModal from '@/components/PreviewModal'
import SupplierSelect from '../../components/SupplierSelect'
import pick from 'lodash.pick'

export default {
  components: {
    PreviewModal,
    SupplierSelect
  },
  data() {
    return {
      idcardZ,
      idcardF,
      demoImg,
      imageUrl: '',
      idcardFront: [], // 身份证正面图片显示数组
      idcardBack: [], // 身份证反面图片显示数组
      qualificationList: [], // 购销资格证图片显示数组
      visible: false,
      isEdit: false,
      form: {
        linkmanId: null,
        supplierCode: null,
        linkmanName: null,
        linkmanTitle: null,
        salesmanFlag: false,
        idcard: null,
        idcardFront: null,
        idcardEnd: null,
        idcardBack: null,
        qualification: null,
        qualificationEnd: null
      },
      rules: {
        supplierCode: [{ required: true, message: '请选择供应商', trigger: 'blur' }],
        linkmanName: [{ required: true, message: '请输入联系人姓名', trigger: 'blur' }],
        linkmanTitle: [{ required: true, message: '请输入联系人头衔', trigger: 'blur' }],
        linkmanTel: [{ required: true, message: '请输入联系电话', trigger: 'blur' }]
      },
      confirmLoading: false,
      mdl: {}, // 存储编辑传递过来的record数据
      imgInfo: {},
      isSaleMan: true,
      qualificationEnd: null,
      salesmanFlag: false,
      selectValue: ''
    }
  },
  methods: {
    edit(bool, record) {
      this.selectValue = ''
      // this.isSaleMan = false
      this.salesmanFlag = false
      this.idcardFront = []
      this.idcardBack = []
      this.qualificationList = []
      console.log('edit', bool, record)
      this.$nextTick(() => {
        this.$refs.form.resetFields()
      })
      this.isEdit = bool
      if (bool) {
        if (record.qualificationEnd) {
          this.qualificationEnd = record.qualificationEnd
        }
        this.selectValue = record.supplierCode
        // this.isSaleMan = record.salesmanFlag
        this.salesmanFlag = record.salesmanFlag
        // 通过 linkmanId 去查已上传的图片回显过来
        showUrlById(record.linkmanId).then(res => {
          console.log('res', res)
          if (res.data) {
            if (res.data.idcardFront) {
              this.idcardFront = [{ uid: '0', name: 'idcardFront', url: res.data.idcardFrontSavePath }]
            }
            if (res.data.idcardBack) {
              this.idcardBack = [{ uid: '1', name: 'idcardBack', url: res.data.idcardBackSavePath }]
            }
            if (res.data.qualification) {
              this.qualificationList = [{ uid: '2', name: 'qualification', url: res.data.qualificationkSavePath }]
            }
          }
        })
      }
      this.mdl = Object.assign({}, record)
      this.$nextTick(() => {
        this.form = pick(this.mdl, 'idcardFront', 'idcardBack', 'qualification', 'linkmanId', 'linkmanName', 'supplierCode', 'linkmanTitle', 'linkmanTel', 'salesmanFlag', 'idcard', 'idcardEnd')
      })
      this.visible = true
    },
    async handleOk(e) {
      e.stopPropagation()

      this.$refs.form.validate(async valid => {
        if (valid) {
          this.confirmLoading = true

          const param = { ...this.form, qualificationEnd }
          console.log('param', param)
          if (isEdit) {
            const res = await updateLinkMan(param)
          } else {
            const res = await insertLinkMan(param)
          }
          const mes = isEdit ? '修改操作成功' : '新增操作成功'
          openNotification('success', mes)
          this.visible = false
          this.$emit('refresh')
          this.confirmLoading = false
        }
      })

      // const {
      //   form: { validateFields },
      //   isEdit,
      //   qualificationEnd
      // } = this
      // this.confirmLoading = true

      // validateFields(
      //   ['linkmanId', 'linkmanName', 'idcardFront', 'idcardBack', 'qualification', 'linkmanTitle', 'supplierCode', 'linkmanTel', 'salesmanFlag', 'idcard', 'idcardEnd', 'qualificationEnd'],
      //   { force: true },
      //   async (err, values) => {
      //     if (!err) {
      //       const { qualification, qualificationEnd, salesmanFlag } = values
      //       if (salesmanFlag) {
      //         if (qualification && qualificationEnd) {
      //           // 勾选业务员，且证件和日期已填
      //           console.log('people values', { ...values, qualificationEnd })
      //           //this.$emit('sendData', { ...values, qualificationEnd }, 3)
      //         } else {
      //           this.$message.error('业务员必须上传购销资格证')
      //           this.confirmLoading = false
      //           return false
      //         }
      //       }
      //       const param = { ...values, qualificationEnd }
      //       console.log('param', param)
      //       if (isEdit) {
      //         const res = await updateLinkMan(param)
      //       } else {
      //         const res = await insertLinkMan(param)
      //       }
      //       const mes = isEdit ? '修改操作成功' : '新增操作成功'
      //       openNotification('success', mes)
      //       this.visible = false
      //       this.$emit('refresh')
      //     }
      //     this.confirmLoading = false
      //   }
      // )
    },
    handleCancel() {
      this.visible = false
    },
    // 勾选是否业务员
    saleManChange(e) {
      this.isSaleMan = e
      this.salesmanFlag = e
    },
    // 预览图片，显示大图
    handlePreview(file) {
      this.$refs.previewModal.show([file.url])
    },
    handleChange(info, arr) {
      console.log('info', info, arr)
      this.imgInfo = info
      switch (arr) {
        case 1:
          this.idcardFront = info.fileList
          break
        case 2:
          this.idcardBack = info.fileList
          break
        default:
          this.qualificationList = info.fileList
          break
      }
      arr = info.fileList
      if (info.file.status === 'uploading') {
        this.loading = true
        return
      }
      if (info.file.status === 'done') {
        // Get this url from response in real world.
        getBase64(info.file.originFileObj, imageUrl => {
          this.imageUrl = imageUrl
          console.log('info', info, arr, imageUrl)
          this.loading = false
        })
      }
    },
    handleRemove(info, type) {
      console.log('remove info', info)
      let id = ''
      if (type === 'front') {
        id = this.form.idcardFront
        this.idcardFront = []
        this.$nextTick(() => {
          this.$set(this.form, 'idcard', '')
        })
      } else if (type === 'back') {
        id = this.form.idcardBack
        this.idcardBack = []
        this.$nextTick(() => {
          this.$set(this.form, 'idcardEnd', '')
        })
      } else {
        id = this.form.qualification
        this.qualificationList = []
        this.$nextTick(() => {
          this.$set(this.form, 'qualification', '')
          this.$set(this.form, 'qualificationEnd', '')
        })
      }
    },
    // 覆盖原本的上传方法
    customRequest(info, local) {
      console.log('customRequest', info)
      const formData = new FormData()
      formData.append('file', info.file)
      // 调方法，post，body 放入 formData
      if (local === 'front') {
        idcardFrontUpload(formData).then(res => {
          if (res.data !== null) {
            const { data } = res
            console.log('imgInfo', this.imgInfo)
            this.idcardFront = [{ ...this.imgInfo.fileList[0], status: 'done', url: data[0].savePath }]
            this.$nextTick(() => {
              this.$set(this.form, 'idcard', data[1].idCardNum)
              this.$set(this.form, 'idcardFront', data[0].uploadId)
              this.$set(this.form, 'linkmanName', data[1].name)
            })
          }
        })
      } else if (local === 'back') {
        idcardBackUpload(formData).then(res => {
          if (res.data !== null) {
            const { data } = res
            console.log('data', data)
            this.idcardBack = [{ ...this.imgInfo.fileList[0], status: 'done', url: data[0].savePath }]
            const expiryDate = data[1].expiryDate
            const year = expiryDate.substr(0, 4)
            const mon = expiryDate.substr(4, 2)
            const day = expiryDate.substr(6, 2)
            const date = year + '-' + mon + '-' + day
            console.log('date', year, mon, day)
            this.$nextTick(() => {
              this.$set(this.form, 'idcardEnd', date)
              this.$set(this.form, 'idcardBack', data[0].uploadId)

              // this.form.setFieldsValue({
              //   idcardEnd: date,
              //   idcardBack: data[0].uploadId
              // })
            })
          }
        })
      } else {
        saveOnlyUploads(formData).then(res => {
          if (res.data !== null) {
            const { data } = res
            console.log('res', res)
            this.qualificationList = [{ ...this.imgInfo.fileList[0], status: 'done', url: data[0].savePath }]
            this.$nextTick(() => {
              this.$set(this.form, 'qualification', data.uploadId)
            })
          }
        })
      }
    },
    handleSelect(value) {
      this.$set(this.form, 'supplierCode', value)
    }
  }
}
</script>

<style scoped>
.w330 {
  width: 230px;
}
.avatar-uploader >>> .ant-upload-list-item {
  width: 258px;
  height: 189px;
}
.edit-people-form >>> .supplier-label {
  width: 100%;
}
.edit-people-form >>> .supplier-label .el-form-item__label {
  width: 70px !important;
}
.edit-people-form >>> .supplier-label .el-form-item__content {
  width: 90% !important;
}
.edit-people-form >>> .name-label .el-form-item__label {
  width: 40px !important;
}
.edit-people-form >>> .date-label .el-form-item__label {
  width: 120px !important;
}
.edit-people-form >>> .date-label1 .el-form-item__label {
  width: 140px !important;
}
/* .edit-people-form >>> .phone-label .el-form-item-label {
  width: 151px;
} */
/* .edit-people-form >>> .date-label .el-form-item__label {
  width: 156px !important;
} */
</style>
